package com.fessc.develop.handler.processor.request;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fessc.develop.base.Result;
import com.fessc.develop.entity.comvo.*;
import com.fessc.develop.entity.dbvo.TIdentityVerify;
import com.fessc.develop.entity.dbvo.TOrgUrlManage;
import com.fessc.develop.handler.SignHandler;
import com.fessc.develop.model.enums.*;
import com.fessc.develop.service.interfaces.ITIdentityVerifyService;
import com.fessc.develop.service.interfaces.ITOrgUrlManageService;
import com.fessc.develop.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Service
public class ComIdentityRegisterService implements IBaseService {

    @Resource
    private SignHandler signHandler;

    @Resource
    private ITOrgUrlManageService tOrgUrlManageService;

    @Resource
    private ITIdentityVerifyService identityVerifyService;

    @Resource
    private OkHttpUtil okHttpUtil;

    @Override
    public String getServiceCode() {
        return EnumServiceCode.COM_BS0003.toString();
    }

    @Override
    public Result process(JSONObject request) {
        log.info("银行核验边民开户请求报文: " + request.toJSONString());
        Result result = new Result();
        String errorCode = "";
        IdentityRegisterResVo identityRegisterResVo = new IdentityRegisterResVo();
        IdentityRegisterReqVo identityRegisterReqVo = JSON.parseObject(request.getJSONObject(EnumJsonProperty.REQ_BODY.toString()).toJSONString(), IdentityRegisterReqVo.class);
        SysHeadVo sysHeadVo = JSON.parseObject(request.getJSONObject(EnumJsonProperty.REQ_SYS_HEAD.toString()).toJSONString(), SysHeadVo.class);

        // 检查请求报文各个字段内容是否符合要求
        if (BusiUtil.isNull(identityRegisterReqVo.getChkTp())) {
            errorCode = "EE1019";
        } else if (BusiUtil.isNotEquals(identityRegisterReqVo.getChkTp(), "1") &&
                BusiUtil.isNotEquals(identityRegisterReqVo.getChkTp(), "2") &&
                BusiUtil.isNotEquals(identityRegisterReqVo.getChkTp(), "3") &&
                BusiUtil.isNotEquals(identityRegisterReqVo.getChkTp(), "4")) {
            errorCode = "EE1020";
        } else if (BusiUtil.isNull(identityRegisterReqVo.getName())) {
            errorCode = "EE1021";
        } else if (BusiUtil.isNull(identityRegisterReqVo.getCrdtNo())) {
            errorCode = "EE1022";
        } else if (BusiUtil.isNull(identityRegisterReqVo.getCrdtTp())) {
            errorCode = "EE1023";
        } else if (BusiUtil.isNull(identityRegisterReqVo.getNat())) {
            errorCode = "EE1024";
        }

        // 报文内容错误
        if (BusiUtil.isNotNull(errorCode)) {
            result = new Result(EnumResultType.SUCCESS.getStatusCode(), EnumResultType.SUCCESS.getMsg());
            identityRegisterResVo.setPcsgRlt(ErrorUtil.getErrorDesc(errorCode));
            identityRegisterResVo.setFalRs(errorCode);
            result.setData(identityRegisterResVo);
            return result;
        }

        switch (identityRegisterReqVo.getChkTp()) {
            case "1":
                //todo:查询市场交易平台边民注册信息
                result = peopleIdentityRegister(identityRegisterReqVo, sysHeadVo);
                break;
            case "2":
                //todo:查询市场交易平台商铺注册信息
                result = peopleIdentityRegister(identityRegisterReqVo, sysHeadVo);
                break;
            default:
                //todo:报错
                throw ExceptionUtil.businessException("EE4013");
        }
        log.info("银行核验边民开户返回报文: " + JSON.toJSONString(result));
        return result;
    }

    /**
     * 查询是否边民允许开立虚户
     */
    private Result peopleIdentityRegister(IdentityRegisterReqVo identityRegisterReqVo, SysHeadVo sysHeadVo) {
        //组装发送公共交易中心报文
        CommonSendVo<Object> commonSendVo = new CommonSendVo<>();
        sysHeadVo.setServiceCode(EnumServiceCode.PLAT_MP0001.toString());
        CommonHeadSendVo commonHeadSendVo = new CommonHeadSendVo();
        BeanUtils.copyProperties(sysHeadVo, commonHeadSendVo);
        commonSendVo.setCommonHeadSendVo(commonHeadSendVo);
        commonSendVo.setBody(identityRegisterReqVo);
        log.info("互联互通转发核验边民开户请求明文: " + JSON.toJSONString(commonSendVo));

        //根据机构查询配置表获取URL，通用默认一个机构只有一个URL
        TOrgUrlManage orgUrlManage = tOrgUrlManageService.getOrgUrlByOrgCodeAndKey(sysHeadVo.getOrgCode(), EnumOrgType.OTHER.toString(), EnumServiceCode.PLAT_MP0001.toString());
        String afterEncrypt = signHandler.encrypt(JSON.toJSONString(identityRegisterReqVo), orgUrlManage.getPubCert());
        commonSendVo.setBody(afterEncrypt);
        Map<String, String> requestHeaders = okHttpUtil.getRequestHeaders(orgUrlManage.getAppKey(), orgUrlManage.getInterfaceUrl(), commonHeadSendVo.getBankId());
        log.info("互联互通转发核验边民开户请求密文：" + JSON.toJSONString(commonSendVo));

        //接口推送
        String responseEncryptJson = "";  //返回加密报文
        JSONObject responseDecryptJson = new JSONObject();  //解密后报文
        try {
            // 先解析返回报文
            responseEncryptJson = okHttpUtil.doPostJson(orgUrlManage.getInterfaceUrl(), JSON.toJSONString(commonSendVo), requestHeaders);
            responseDecryptJson = JSON.parseObject(responseEncryptJson);
            log.info("核验边民开户响应报文(解密前): " + JSON.toJSONString(responseDecryptJson));
            String date = responseDecryptJson.getString(EnumJsonProperty.RES_DATA.toString());
            // 解密DATA部分
            if (BusiUtil.isNotNull(date)) {
                responseDecryptJson.put(EnumJsonProperty.RES_DATA.toString(), JSONObject.parseObject(signHandler.decrypt(date)));
            }
            log.info("核验边民开户响应报文(解密后): " + JSON.toJSONString(responseDecryptJson));
        } catch (Exception e) {
            log.info("核验边民开户响应报文解析失败: " + e.getMessage());
        }

        //保存银行查询核验边民开户信息
        try {
            log.info("保存银行核验边民开户信息：" + identityRegisterReqVo.getName() + "，" + identityRegisterReqVo.getCrdtNo());
            TIdentityVerify identityVerify = new TIdentityVerify();
            identityVerify.setLogId(MDC.get("lodId"));
            identityVerify.setBankId(sysHeadVo.getBankId());
            identityVerify.setOrgCode(sysHeadVo.getOrgCode());
            identityVerify.setVerifyType(identityRegisterReqVo.getChkTp());
            identityVerify.setName(identityRegisterReqVo.getName());
            identityVerify.setCardType(identityRegisterReqVo.getCrdtTp());
            identityVerify.setCardNo(identityRegisterReqVo.getCrdtNo());
            identityVerify.setNat(identityRegisterReqVo.getNat());
            identityVerify.setRequestTime(DateUtil.getCurrentLocalDateTime());
            identityVerify.setOrgCode(sysHeadVo.getOrgCode());
            identityVerify.setResponseCode(responseDecryptJson.getJSONObject(EnumJsonProperty.RES_DATA.toString()).getString("ChkRes"));
            identityVerify.setResponseLog(responseDecryptJson.getJSONObject(EnumJsonProperty.RES_DATA.toString()).getString("ChkMsg"));
            identityVerifyService.save(identityVerify);
        } catch (Exception e) {
            log.info("保存银行核验边民开户信息异常: " + e.getMessage());
        }

        // 返回报文
        Result result = new Result(responseDecryptJson.getString(EnumJsonProperty.RES_STATUS_CODE.toString()), responseDecryptJson.getString(EnumJsonProperty.RES_STATUS_MSG.toString().toUpperCase()));
        result.setData(responseDecryptJson.getJSONObject(EnumJsonProperty.RES_DATA.toString()));
        return result;
    }

}
